package cn.globalph.housekeeper.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class AlertDialogFragment extends DialogFragment {
    private AlertDialog.Builder builder;


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog dialog = builder.create();
        return dialog;
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (manager.isDestroyed()) {
                return;
            }
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }

    public void setBuilder(AlertDialog.Builder builder){
        this.builder = builder;
    }

    public static class MyBuilder {
        AlertDialog.Builder builder;
        private boolean cancelable = true;

        public MyBuilder(Context context){
            builder = new AlertDialog.Builder(context);
        }

        public MyBuilder setTitle(String title){
            builder.setTitle(title);
            return this;
        }

        public MyBuilder setMessage(String message){
            builder.setMessage(message);
            return this;
        }

        public MyBuilder setPositiveButton(String name, DialogInterface.OnClickListener listener){
            builder.setPositiveButton(name,listener);
            return this;
        }

        public MyBuilder setCancelable(boolean cancelable){
            this.cancelable = cancelable;
            builder.setCancelable(cancelable);
            return this;
        }

        public MyBuilder setNegativeButton(String name, DialogInterface.OnClickListener listener){
            builder.setNegativeButton(name,listener);
            return this;
        }

        public AlertDialogFragment create(){
            AlertDialogFragment dialogFragment = new AlertDialogFragment();
            dialogFragment.setBuilder(builder);
            dialogFragment.setCancelable(cancelable);
            return dialogFragment;
        }

        public Boolean getCancelable(){
            return cancelable;
        }
    }
}
